<?php

namespace App\Console\Commands\Cruise;

use App\Models\BaseModel;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckTaskModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseTaskOrderMappingModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Service\Cruise\Check\CruiseCheckTaskService;
use Carbon\Carbon;
use Illuminate\Console\Command;

class CheckOrderCancel extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:check_order_cancel';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动作废过期订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //获得要作废的任务ID
        $cruiseTaskIdsSql = CruiseCheckTaskModel::query()
            ->whereIn('status', [CruiseCheckTaskModel::STATUS_WAIT_PUSH, CruiseCheckTaskModel::STATUS_ING])
            ->whereIn('type', [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_5])
            ->where('endTime', '<', time())
            ->where('endTime', '>', Carbon::now()->subDay()->timestamp)
            ->select(['id']);

        $cruiseOrderIds = CruiseTaskOrderMappingModel::query()
            ->whereRaw("taskId in (" . BaseModel::toSqlWithParam($cruiseTaskIdsSql) . ")")
            ->join('cruise_order', 'cruise_order.id', '=', 'cruise_task_order_mappings.orderId')
            ->whereIn('cruise_order.status', [CruiseOrderModel::STATUS_INIT, CruiseOrderModel::STATUS_NOT_SUBMIT, CruiseOrderModel::STATUS_COLLECTED])
            ->pluck('cruise_task_order_mappings.orderId')
            ->toArray();

        foreach ($cruiseOrderIds as $cruiseOrderId) {
            try {
                CruiseCheckTaskService::orderCancel($cruiseOrderId, 0, false);
            } catch (\Exception $exception) {}
        }

    }
}
